/*
 * @Author: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @Date: 2023-04-13 16:50:13
 * @LastEditors: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @LastEditTime: 2023-04-13 17:42:53
 * @FilePath: \ant-design-vue-admin-master\src\store\modules\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { constantRouterMap, otherRouterMap } from '@/router/router.config'
import router, { asyncRouterMap } from '@/router'

import Router from 'vue-router'

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param frontRoutes
 * @param roles
 */

function filterAsyncRouter (frontRoutes, roles) {
  return frontRoutes
    .filter(item => roles[item.authorityCode])
    .map(route => {
      const sort = roles[route.authorityCode].sort || 0
      const tempRoute = Object.assign({ sort }, route)
      if (route.url) {
        tempRoute.path = route.url
      }
      if (tempRoute.children) {
        tempRoute.children = filterAsyncRouter(route.children, roles).sort((a, b) => a.sort - b.sort)
      }
      return tempRoute
    })
}

function getRouteTree (routes) {
  const tempEntries = routes.reduce(
    (prev, cur) => ({
      ...prev,
      [cur.code]: cur
    }),
    {}
  )
  const finalRoutes = filterAsyncRouter(asyncRouterMap, tempEntries)
  console.log('finalRoutes', finalRoutes)
  return finalRoutes.concat(otherRouterMap)
}
const permission = {
  state: {
    routers: [],
    addRouters: []
  },

  getters: {
    permission_routers: state => state.routers,
    permission_menus: state =>
      state.routers.filter(item => {
        return item.alwaysShow
      }),
    addRouters: state => state.addRouters
  },

  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.routers = state.routers.concat(constantRouterMap).concat(routers)
      state.addRouters = state.routers
      router.matcher = new Router().matcher
      for (const route of state.routers) {
        router.addRoute(route) // 动态添加可访问路由
      }
      console.log('router', state.routers)
    },
    SET_SIDE_VIEW: (state, routers) => {
      state.addRouters = routers
    }
  },
  actions: {
    GenerateRoutes ({ commit, state }, { authorityResults }) {
      return new Promise((resolve, reject) => {
        try {
          const accessedRouters = getRouteTree(authorityResults || [])
          console.log('accessedRouters', accessedRouters)
          commit('SET_ROUTERS', accessedRouters)
          resolve({ errorMessage: '' })
        } catch (err) {
          reject(err)
        }
      })
    }
  }
}

export default permission
